package com.phpxiu.app.view;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.phpxiu.app.adapter.C2CChatListAdapter;
import com.phpxiu.app.api.callback.MsgCountManager;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.event.OnBlockEvent;
import com.phpxiu.app.model.event.OnChatPhotoEvent;
import com.phpxiu.app.model.msg.C2CImageMsg;
import com.phpxiu.app.model.msg.C2CMsg;
import com.phpxiu.app.model.msg.C2CMsgFactory;
import com.phpxiu.app.model.msg.C2CTextMsg;
import com.phpxiu.app.model.msg.C2CVoiceMsg;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.OKHttpResponseModel;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.presenters.C2CChatPresenter;
import com.phpxiu.app.presenters.viewinterface.C2CChatView;
import com.phpxiu.app.utils.FileManager;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.utils.VoiceManager;
import com.phpxiu.app.view.custom.ChatInput;
import com.phpxiu.app.view.custom.VoiceSendingView;
import com.phpxiu.app.view.dialog.PhotoOptionMenus;
import com.tencent.TIMConversationType;
import com.tencent.TIMMessage;
import com.tencent.TIMMessageStatus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/**
 * @file
 * @brief 私信聊天界面
 * @author 吴金洲
 * @note 以列表展示聊天消息，发送消息：文本、表情、语音及图片等消息
 *
 */
public class C2CChat extends UIBase implements C2CChatView,View.OnClickListener {
    private final static String TAG = "C2CChat";
    public final static String EXTRA_CONVERSATION_ID="extra_conversation_id";
    public final static String EXTRA_USER_ID="extra_user_id";
    public final static String EXTRA_USER_NICK_NAME="extra_user_nick_name";
    public final static String EXTRA_USER_AVATAR="extra_user_avatar";
    public final static String EXTRA_BLOCK_SING="extra_block_sign";//黑名单标志
    private List<C2CMsg> messageList = new ArrayList<C2CMsg>();
    private C2CChatListAdapter adapter;
    private ListView listView;
    private C2CChatPresenter presenter;
    private ChatInput input;
    private VoiceSendingView voiceSendingView;
    private String identify;
    private String nickName;
    private String avatar;
    private TextView nickView;
    private boolean isBlock=false;//是否为拉黑状态
    private Uri fileUri;
    private boolean isRefreshMsgCount=true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.c2c_chat);
        EventBus.getDefault().register(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        identify = getIntent().getStringExtra(EXTRA_CONVERSATION_ID);
        nickName=getIntent().getStringExtra(EXTRA_USER_NICK_NAME);
        avatar=getIntent().getStringExtra(EXTRA_USER_AVATAR);
        String block=getIntent().getStringExtra(EXTRA_BLOCK_SING);
        if("1".equals(block)){
            isBlock=true;//黑名单状态
        }
        nickView=(TextView)findViewById(R.id.title);
        nickView.setText(nickName);
        presenter = new C2CChatPresenter(this, identify, TIMConversationType.C2C);
        input = (ChatInput) findViewById(R.id.input_panel);//输入栏
        input.setChatView(this);
        voiceSendingView = (VoiceSendingView) findViewById(R.id.voice_sending_view);//语音录制状态视图
        adapter = new C2CChatListAdapter(this,messageList,avatar);
        listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(adapter);
        listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
        listView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        input.setInputMode(ChatInput.InputMode.NONE);
                        break;
                }
                return false;
            }
        });
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            private int firstItem;
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && firstItem == 0) {
                    //如果拉到顶端读取更多消息
                    presenter.getMessage(messageList.size() > 0 ? messageList.get(0).getMessage() : null);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                firstItem = firstVisibleItem;
            }
        });
        presenter.start();
        isRefreshMsgCount=true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_bar_back_btn:
                onBackPressed();
                break;
            default:
                break;
        }
    }

    /**
     * 显示消息
     *
     * @param message
     */
    @Override
    public void showMessage(TIMMessage message) {
        if (message == null) {
            adapter.notifyDataSetChanged();
        } else {
            C2CMsg mMessage = C2CMsgFactory.getMessage(message);
            if (mMessage != null) {
                if (messageList.size()==0){
                    mMessage.setShowTime(null);
                }else{
                    mMessage.setShowTime(messageList.get(messageList.size()-1).getMessage());
                }
                messageList.add(mMessage);
                adapter.notifyDataSetChanged();
                listView.setSelection(adapter.getCount()-1);
            }
        }

    }

    /**
     * 显示消息
     *
     * @param messages
     */
    @Override
    public void showMessage(List<TIMMessage> messages) {
        int newMsgNum = 0;
        for (int i = 0; i < messages.size(); ++i){
            C2CMsg mMessage = C2CMsgFactory.getMessage(messages.get(i));
            if(messages.get(i).status() == TIMMessageStatus.HasDeleted){
                KKYUtil.log("已被删除："+messages.get(i).getSender());
            }
            if (mMessage == null || messages.get(i).status() == TIMMessageStatus.HasDeleted) continue;
            ++newMsgNum;
            if (i != messages.size() - 1){
                mMessage.setShowTime(messages.get(i+1));
                messageList.add(0, mMessage);
            }else{
                messageList.add(0, mMessage);
            }
        }
        adapter.notifyDataSetChanged();
        listView.setSelection(newMsgNum);
    }

    /**
     * 清除所有消息，等待刷新
     */
    @Override
    public void clearAllMessage() {
        messageList.clear();
    }

    /**
     * 发送消息成功
     *
     * @param message 返回的消息
     */
    @Override
    public void onSendMessageSuccess(TIMMessage message) {
        if(isBlock){//黑名单状态,是否解除黑名单
            isBlock=false;
            KKYUtil.log("主动发消息解除黑名单:" + message.getConversation().getPeer());
            delBlackList(message.getConversation().getPeer());
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * 解除黑名单
     * @param peer
     */
    private void delBlackList(String peer){
        OKHttpParam param=OKHttpParam.builder(false);
        param.put("uid",peer);
        OKHttp.post(HttpConfig.API_ADD_CANCEL_BLOCK_BY_UID, param.jsonParam(), TAG, new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                KKYUtil.log("主动发消息解除黑名单同步成功");
            }

            @Override
            public void onErr(String errMsg) {

            }
        });
    }

    /**
     * 发送消息失败
     *
     * @param code 返回码
     * @param desc 返回描述
     */
    @Override
    public void onSendMessageFail(int code, String desc,TIMMessage message) {
        switch (code){
            case 80001:
                //发送内容包含敏感词
                getString(R.string.bad_word);
                break;
        }
    }

    /**
     * 发送文本消息
     */
    @Override
    public void sendText() {
        C2CMsg message = new C2CTextMsg(input.getText());
        presenter.sendMessage(message.getMessage());
        input.setText("");
    }

    /**
     * 开始发送语音消息
     */
    @Override
    public void startSendVoice() {
        voiceSendingView.setVisibility(View.VISIBLE);
        voiceSendingView.showRecording();
        VoiceManager.getInstance().startRecording();
    }

    /**
     * 结束发送语音消息
     */
    @Override
    public void endSendVoice() {
        voiceSendingView.release();
        voiceSendingView.setVisibility(View.GONE);
        VoiceManager.getInstance().stopRecording();
        if (VoiceManager.getInstance().getTimeInterval() < 1) {
            Toast.makeText(this, getResources().getString(R.string.msg_voice_invalid), Toast.LENGTH_SHORT).show();
        } else {
            C2CMsg message = new C2CVoiceMsg(VoiceManager.getInstance().getTimeInterval(), VoiceManager.getInstance().getFilePath());
            presenter.sendMessage(message.getMessage());
        }
    }


    /**
     * 结束发送语音消息
     */
    @Override
    public void cancelSendVoice() {

    }

    @Override
    protected void onPause(){
        super.onPause();
        VoiceManager.getInstance().stop();
    }

    /**
     * 拉黑事件
     */
    @Subscribe
    public void onBlock(OnBlockEvent event){
       if (event.getPeer().equals(identify)){
           finish();
       }
    }
    /**
     * 发送图片消息
     */
    @Override
    public void sendImage() {
        Intent album = new Intent();
        album.setType("image/*");
        album.setAction(Intent.ACTION_GET_CONTENT);
        album.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(Intent.createChooser(album,getString(R.string.system_photo_title)),PhotoOptionMenus.REQUEST_PHOTO_CODE);
    }

    /**
     * 发送照片消息
     */
    @Override
    public void sendPhoto() {
        Intent capture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (capture.resolveActivity(getPackageManager()) != null) {
            File tempFile = FileManager.getTempFile(FileManager.FileType.IMG);
            if (tempFile != null) {
                fileUri = Uri.fromFile(tempFile);
            }
            capture.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
            startActivityForResult(capture,PhotoOptionMenus.REQUEST_CAPTURE_CODE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PhotoOptionMenus.REQUEST_CAPTURE_CODE) {//从相机发达图片
            if (resultCode == RESULT_OK && fileUri != null) {
                showImagePreview(fileUri);
            }else{
                fileUri=null;
            }
        } else if (requestCode == PhotoOptionMenus.REQUEST_PHOTO_CODE) {//从相册发送图片
            if (resultCode == RESULT_OK && data != null) {
                fileUri=data.getData();
                showImagePreview(fileUri);
            }else{
                fileUri=null;
            }
        }  else if (requestCode == PhotoOptionMenus.REQUEST_PREVIEW_CODE){
            if (resultCode == RESULT_OK) {
                if(fileUri==null){
                    Toast.makeText(this,"Not found file",Toast.LENGTH_LONG).show();
                    return;
                }
                String path=FileManager.getFilePath(this,fileUri);
                File file = new File(path);
                if (file.exists() && file.length() > 0){
                    if (file.length() > 1024 * 1024 * 10){
                        //文件太大
                        Toast.makeText(this,"File is too large",Toast.LENGTH_LONG).show();
                    }else{
                        C2CMsg message = new C2CImageMsg(path,true);
                        presenter.sendMessage(message.getMessage());
                    }
                }else{
                    //找不到文件
                    Toast.makeText(this,"Not found file!",Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    /**
     * 发送图片预览
     * @param uri
     */
    private void showImagePreview(Uri uri){
        if (uri == null) return;
        Intent preview=new Intent(this,PicturePreview.class);
        preview.putExtra(PicturePreview.PREVIEW_ACTION,PicturePreview.SEND);
        preview.setData(uri);
        startActivityForResult(preview,PhotoOptionMenus.REQUEST_PREVIEW_CODE);
    }

    /**
     * 显示图片
     */
    @Subscribe
    public void showImage(OnChatPhotoEvent event){
        Intent preview=new Intent(this,PicturePreview.class);
        String url=event.getUrl();
        preview.putExtra(PicturePreview.PREVIEW_ACTION,PicturePreview.SAVE);
        if(url!=null&&!"".equals(url)&&url.startsWith("http")){//网络图片
            preview.putExtra(PicturePreview.PREVIEW_URL,url);
        }
        preview.setData(event.getUri());
        startActivity(preview);
    }

    @Override
    public void finish() {
        if(isRefreshMsgCount){
            isRefreshMsgCount=false;
            MsgCountManager.getInstance().refreshMsgCount();
        }
        super.finish();
    }

    @Override
    protected void onDestroy() {
        presenter.stop();
        EventBus.getDefault().unregister(this);
        if(isRefreshMsgCount){
            isRefreshMsgCount=false;
            MsgCountManager.getInstance().refreshMsgCount();
        }
        super.onDestroy();
    }


}
